#!coding=utf-8

import os

from PIL import Image
from pyzbar.pyzbar import decode

class QrCodeRecongnize():
    '''
    file_path:文件路径
    '''
    def __init__(self,file_path):
        self.file_path = file_path

    # 读取二维码
    def qr_code(self):
        # 打开二维码
        img = Image.open(self.file_path)
        # 灰度化
        img = img.convert("L")
        # 编码
        barcodes = decode(img)
        # print barcodes
        # 图片名称
        file_name = file_path.split("\\") if len(file_path.split('\\')) > 1 else file_path.split('/')
        print(barcodes)
        if barcodes:
            barcode_data = ''
            barcode_list = []
            # 若一张图片有两个二维码
            for barcode in barcodes:
                barcode_data = barcode.data.decode('utf-8')
                # 判断类型
                if 'wxp' in barcode_data:
                    barcode_list.append([file_name[-1], 'WeChatPay', barcode_data])
                elif 'alipay' in barcode_data:
                    barcode_list.append([file_name[-1], 'AliPay', barcode_data])
                else:
                    barcode_list.append([file_name[-1], 'other', barcode_data])
            return barcode_list
        else:
            return [file_name[-1], 'loser','']


if __name__ == '__main__':
    file_path = r"./20200621123926.jpg"
    # file_path = r"img\22.png"
    # file_path = r"img/60.png"

    q = QrCodeRecongnize(file_path)
    c = q.qr_code()
    print(c)
